package com.zh.harmony.ormlitesample.util;


import com.j256.ormlite.harmony.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.zh.harmony.ormlitesample.entity.ArticleEntity;
import com.zh.harmony.ormlitesample.entity.UserEntity;
import ohos.app.Context;
import ohos.data.rdb.RdbStore;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * @author wally
 * @date 2022/08/09
 * <p>
 * App数据库管理类
 */
public class AppDatabaseHelper extends OrmLiteSqliteOpenHelper {
    /**
     * 数据库名称
     */
    private static final String DATABASE_NAME = "app.db";
    /**
     * 数据库版本号
     */
    private static final int DATABASE_VERSION = 1;
    /**
     * 单例
     */
    private static volatile AppDatabaseHelper sInstance;

    /**
     * 获取所有表实体列表
     */
    private List<Class<?>> getTableEntities() {
        return Arrays.asList(
                UserEntity.class,
                ArticleEntity.class
        );
    }

    public static AppDatabaseHelper getInstance() {
        if (sInstance == null) {
            synchronized (AppDatabaseHelper.class) {
                if (sInstance == null) {
                    sInstance = new AppDatabaseHelper(ContextUtil.getContext());
                }
            }
        }
        return sInstance;
    }

    private AppDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, DATABASE_VERSION);
    }

    @Override
    public void onCreate(RdbStore database, ConnectionSource connectionSource) {
        //创建表
        for (Class<?> entity : getTableEntities()) {
            try {
                TableUtils.createTable(connectionSource, entity);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void onUpgrade(RdbStore database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        //数据库升级，开发阶段，清空数据，重新创建
        for (Class<?> entity : getTableEntities()) {
            try {
                TableUtils.dropTable(connectionSource, entity, true);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        onCreate(database, connectionSource);
    }
}